package work.chenbo.spring_boot_shiro.modules.sys_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import work.chenbo.spring_boot_shiro.common.util.CodecUtils;
import work.chenbo.spring_boot_shiro.modules.sys_user.constant.ErrorCodeEnum;
import work.chenbo.spring_boot_shiro.modules.sys_user.dao.mapper.*;
import work.chenbo.spring_boot_shiro.modules.sys_user.entity.*;
import work.chenbo.spring_boot_shiro.modules.sys_user.service.SysUserService;
import work.chenbo.spring_boot_shiro.modules.sys_user.vo.UserQO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @className SysUserServiceImpl
 * @authtor ChenBo
 * @date 2019/10/27
 */
@Slf4j
@Transactional
@Service
public class SysUserServiceImpl implements SysUserService {


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;


    /**
     * 获取Mapper
     *
     * @author ChenBo
     * @date 2019/10/30
     */
    @Override
    public BaseMapper<SysUser> getMapper() {
        return sysUserMapper;
    }

    /**
     * 根据用户名获取用户
     *
     * @param userName
     * @author; ChenBo
     * @datetime: 2019/10/27
     */
    @Override
    public SysUser findByUserName(String userName) {
        Long start = System.currentTimeMillis();
        SysUser sysUser = sysUserMapper.findByUserName(userName);
        if(sysUser!=null){ //查询用户角色ID
            List<Long> roleIds = sysUserRoleMapper
                    .selectList(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId,sysUser.getId()))
                    .parallelStream().map(SysUserRole::getRoleId)
                    .collect(Collectors.toList());
            if(!roleIds.isEmpty()){//设置用户角色列表
                List<SysRole> sysRoles = sysRoleMapper.selectBatchIds(roleIds);
                sysUser.setRoles(sysRoles);
                if(!sysRoles.isEmpty()){  //查询角色下权限
                    List<Long> permissionIds = sysRolePermissionMapper
                            .selectList(Wrappers.<SysRolePermission>lambdaQuery().in(SysRolePermission::getRoleId,roleIds))
                            .parallelStream().map(SysRolePermission::getPermissionId)
                            .distinct().filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    if(!permissionIds.isEmpty()){ //设置用户权限列表
                        List<SysPermission> sysPermissions = sysPermissionMapper.selectBatchIds(permissionIds);
                        sysUser.setPermissions(sysPermissions);
                        Long end = System.currentTimeMillis();
                        log.info("查询总共执行时间为:{}",end-start);
                    }
                }
            }
        }
        return sysUser;
    }


    /**
     * 分页查询
     * @param qo
     * @author ChenBo
     * @date 2019/10/30
     */
    @Override
    public IPage<SysUser> queryList(UserQO qo) {

        Page<SysUser> sysUserPage = new Page<>(qo.getCurrent(),qo.getLength());
        IPage<SysUser> sysUserIPage = sysUserMapper.selectByPage(sysUserPage, qo);
        return sysUserIPage;
    }

    /**
     * 页面表单验证用户名是否重复
     *
     * @param userName
     * @author ChenBo
     * @date 2019/11/8
     */
    @Override
    public Boolean checkUserName(Long id,String userName) {
        SysUser sysUser = sysUserMapper.findByUserName(userName);
        if(id != null){
            return sysUser == null || (id.equals(sysUser.getId()));
        }
        return sysUser == null;
    }


    /**
     * 添加用户
     *
     * @param user
     * @author ChenBo
     * @date 2019/11/8
     */
    @Override
    public int add(SysUser user) {
        try{
            user.setCreateTime(new Date());
            SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            user.setCreateBy(loginUser.getId());
            int insert = sysUserMapper.insert(user);
            if(insert>0){
                return ErrorCodeEnum.SUCCESS.getCode();
            }
        }catch (Exception e){
            e.printStackTrace();
            return ErrorCodeEnum.ADD_FAIL.getCode();
        }
        return ErrorCodeEnum.ADD_FAIL.getCode();
    }

    /**
     * 获取用户详细信息
     *
     * @param user
     * @author ChenBo
     * @date 2019/11/12
     */
    @Override
    public SysUser queryOne(SysUser user) {
        return sysUserMapper.selectById(user.getId());
    }
}
